<template>
  <div class="radio-group-box">
    <el-radio
      class="radio-group-item"
      v-model="val"
      v-for="item in options.slice(0,length)"
      :key="item[props.baseId || 'baseId']"
      :label="item[props.baseId || 'baseId']"
    >
      {{ item[props.baseName || 'baseName'] }}
    </el-radio>
    <el-button
      v-show="options.length>max"
      type="text"
      size="medium"
      @click="doExpand"
    >
      {{ isExpand ? '收起' : '更多' }}
    </el-button>
  </div>
</template>

<script>
export default {
  name: 'RadioGroup',
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      val:this.value,
      isExpand: false,
      max: 0,
      btnWidth:0
    }
  },
  props: {
    props: {
      type: Object,
      default: () => {
        return {
          baseId: 'baseId',
          baseName: 'baseName'
        }
      }
    },
    value: {
      type: String,
      default: ''
    },
    options: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  watch: {
    value(val) {
      this.val = val
    },
    val(val) {
      this.$emit('change', val)
    },
    options: {
      handler(val) {
        this.max = this.options.length
        this.$nextTick(()=>{
          this.calcMax()
        })
      },
      immediate:true,
      deep:true
    }
  },
  mounted() {
    this.btnWidth = this.$children[this.$children.length - 1].$el.offsetWidth
  },
  computed: {
    length() {
      if (this.isExpand) {
        return this.options.length
      }

      if (this.options.length > this.max) {
        return this.max
      }

      return this.options.length
    }
  },
  methods: {
    doExpand() {
      this.isExpand = !this.isExpand
    },
    // 计算单行最多显示几个
    calcMax() {
      // 获取展开按钮的宽度
      if(this.$children.length > 0) {
        let width = this.btnWidth
        for (let i = 0; i < this.$children.length -1 ; i++) {
          width = width + this.$children[i].$el.offsetWidth + 20
          if (width > this.$el.parentNode.offsetWidth) {
            this.max = i - 1
            break
          }
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.radio-group-box {
  .radio-group-item {
    margin-right: 20px;

    &:last-child {
      margin-right: 0;
    }
  }

  ::v-deep .el-button {
    font-weight: 400;
  }
}
</style>
